import {
  CanvasTexture,
  ClampToEdgeWrapping,
  LinearFilter,
  PlaneGeometry,
  MeshLambertMaterial,
  Mesh,
} from 'three'

export { updateTexture, getGroundHandler }

function updateTexture(canvas: HTMLCanvasElement, mat: MeshLambertMaterial): MeshLambertMaterial {
  const oldTexture = mat.map
  mat.map = new CanvasTexture(canvas)
  if (oldTexture) oldTexture.dispose()
  return mat
}

/** 通过设置 Mesh.scale 动态调整大小 */
function getGroundHandler(canvas: HTMLCanvasElement) {
  const texture = new CanvasTexture(canvas)
  texture.wrapS = ClampToEdgeWrapping
  texture.wrapT = ClampToEdgeWrapping
  texture.minFilter = LinearFilter

  const geometry = new PlaneGeometry(1, 1)
  const material = new MeshLambertMaterial({ map: texture })
  const mesh = new Mesh(geometry, material)
  mesh.receiveShadow = true

  // 默认平面朝向调整（垂直Y轴转向前方）
  mesh.rotation.x = -Math.PI / 2

  return { mesh, material }
}
